package com.wiloon.java8x.io;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * Created by roy.wang on 2017/4/18;
 */
public class StreamX {
    public static void main(String[] args) {
        try {
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            URL url = classLoader.getResource("foo.txt");
            System.out.println(url);
            System.out.println(url.toURI());

            File file = new File(url.toURI());
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] byteArr = readStream(fileInputStream);
            System.out.println("length:"+byteArr.length);
            for(byte b:byteArr){
                System.out.println(b);
            }
            System.out.println(new String(byteArr));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }
}
